<?php

namespace App\Jobs;

use App\Models\TaskLog;
use App\Services\AudioBookJobService;
use Exception;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;

class AudioBook implements ShouldQueue
{
    use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;

    protected $params;

    /**
     * 任务可尝试的次数。
     *
     * @var int
     */
    public $tries = 3;

    /**
     * 在超时之前任务可以运行的秒数.
     *
     * @var int
     */
    public $timeout = 300;


    /**
     * Create a new job instance.
     */
    public function __construct($params)
    {
        $this->params = $params;
    }

    /**
     * Execute the job.
     */
    public function handle(AudioBookJobService $audioBookJobService)
    {
        $params = $this->params;

        if (empty($params['book_id']) || empty($params['type']) || empty($params['type_name']) || empty($params['log_id'])) {
            throw new Exception('缺少参数');
        }

        $book_id = $params['book_id'];
        $type = $params['type'];
        $type_name = $params['type_name'];
        $log_id = $params['log_id'];

        echo '开始执行 - ' . $type_name . PHP_EOL;

        $jobLog = TaskLog::find($log_id);
        $jobLog->params = json_encode($params);
        $jobLog->status = 1;
        $jobLog->start_time = date('Y-m-d H:i:s');
        $jobLog->save();

        try {
            $audioBookJobService->$type($params);
            $jobLog->status = 2;
            $jobLog->end_time = date('Y-m-d H:i:s');
            $jobLog->save();

            $audioBookJobService->callback($book_id, $type);
        } catch (Exception $e) {
            $result = 'message：' . $e->getMessage() . '，line：' . $e->getLine() . '，file：' . $e->getFile();
            $jobLog->status = -1;
            $jobLog->err_message = $result;
            $jobLog->end_time = date('Y-m-d H:i:s');
            $jobLog->save();

            throw new Exception($e->getMessage());
        }

        return true;
    }
}
